package cn.huiyunche.base.service.interfaces.impl;

import cn.huiyunche.base.service.enums.JourneyTypeEnum;
import cn.huiyunche.base.service.enums.SServiceOrderStatusEnum;
import cn.huiyunche.base.service.enums.UserStatusEnum;
import cn.huiyunche.base.service.enums.WaybillStatusEnum;
import cn.huiyunche.base.service.framework.utils.QiniuUtils;
import cn.huiyunche.base.service.interfaces.CWaybillVeneerService;
import cn.huiyunche.base.service.interfaces.DriverCertInfoService;
import cn.huiyunche.base.service.interfaces.JourneyService;
import cn.huiyunche.base.service.interfaces.UserService;
import cn.huiyunche.base.service.mappers.CJourneyMapper;
import cn.huiyunche.base.service.mappers.CWaybillMapper;
import cn.huiyunche.base.service.model.*;
import cn.huiyunche.base.service.utils.DateUtils;
import cn.huiyunche.base.service.vo.JourneyVo;
import cn.huiyunche.base.service.vo.LoadJourneyPageVo;
import cn.huiyunche.base.service.vo.PageVo;
import cn.huiyunche.base.service.vo.UserVo;
import cn.huiyunche.tools.basic.exceptions.BusinessException;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

@Service

public class JourneyServiceImpl implements JourneyService {

    private static final Logger logger = LoggerFactory.getLogger(JourneyServiceImpl.class);

    @Autowired
    private UserService userService = null;

    @Autowired
    private CJourneyMapper cJourneyMapper = null;

    @Autowired
    private CWaybillMapper cWaybillMapper = null;

    @Autowired
    private CWaybillVeneerService cWaybillVeneerService = null;

    @Autowired
    private DriverCertInfoService driverCertInfoService = null;

    private DriverCertInfoService getDriverCertInfoService() {
        return this.driverCertInfoService;
    }

    private CWaybillVeneerService getCWaybillVeneerService() {
        return this.cWaybillVeneerService;
    }

    @Override
    public long add(CJourney journey, Boolean isVeneer) throws Exception {
        logger.info("The current class JourneyServiceImpl method add start ......");
        UserVo user = this.getUserService().getCurrentUserVo();
        logger.info("The current userId : " + user.getId());
        journey.setUserId(user.getId());
        if (journey.getLatitude() != null || journey.getLongitude() != null
                || StringUtils.isNotBlank(journey.getCurrentAddrDesc())) {
            try {
                this.getCJourneyMapper().insertSelective(journey);
            } catch (Exception e) {
                logger.error("insert journey error : {}", e);
                throw new BusinessException("插入GPS数据错误");
            }
        }

        // 判断用户车辆是否认证通过
        this.getDriverCertInfoService().verifyTheCurrentUservehicleInformationAudit(user.getId(), isVeneer);

        // 用户上线
        this.getUserService().modifyUserStatus(UserStatusEnum.T.getValue());
        logger.info("The current class JourneyServiceImpl method add end ......");
        return 0;
    }

    @Override
    public JourneyVo list() throws Exception {
        logger.info("The current class JourneyServiceImpl method list start ......");
        UserVo user = this.getUserService().getCurrentUserVo();
        logger.info("The current userId : " + user.getId());
        CJourneyExample search = new CJourneyExample();
        CJourneyExample.Criteria criteria = search.createCriteria();
        Date start = DateUtils.StrToDate(DateUtils.getbeforeDay(10) + " 00:00:00");
        Date end = DateUtils.StrToDate(DateUtils.getCurrentDate());
        criteria.andCreateTimeBetween(start, end);
        List<CJourney> journeyList = new ArrayList<CJourney>();
        try {
            journeyList = this.getCJourneyMapper().selectByExample(search);
        } catch (Exception e) {
            logger.error("select error : {}", e);
            throw new BusinessException("数据加载失败");
        }
        List<String> dateList = buildDateList(journeyList);
        Calendar dd = Calendar.getInstance();// 定义日期实例
        dd.setTime(start);// 设置日期起始时间
        JourneyVo vo = new JourneyVo();
        Map<String, String> map = new HashMap<String, String>();
        while (dd.getTime().before(end)) {// 判断是否到结束日期
            SimpleDateFormat sdf = new SimpleDateFormat("MM月dd日");
            String str = sdf.format(dd.getTime());
            if (dateList.contains(str)) {
                map.put(str, JourneyTypeEnum.T.getValue());
            } else {
                map.put(str, JourneyTypeEnum.F.getValue());
            }
            dd.add(Calendar.DATE, 1);// 进行当前天加1
        }
        vo.setDays(dateList.size());
        // TruckInfoVo truckInfoVo = new TruckInfoVo();
        // try {
        // truckInfoVo = this.getTruckInfoService().queryTruckInfo();
        // } catch (Exception e) {
        // logger.error("select TractorNumber error : {}", e);
        // throw new BusinessException("获取车牌号错误");
        // }
        // vo.setTractorNumber(truckInfoVo.getTractorNumber());
        vo.setDateMap(map);
        logger.info("The current class JourneyServiceImpl method list end ......");
        return vo;
    }

    @Override
    public String intradayIsReported() throws Exception {
        UserVo vo = this.getUserService().getCurrentUserVo();
        Date start = DateUtils.StrToDate(DateUtils.getCurrentZeroDate());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd 23:59:59");
        Date end = DateUtils.StrToDate(sdf.format(new Date()));
        CJourneyExample search = new CJourneyExample();
        CJourneyExample.Criteria criteria = search.createCriteria();
        criteria.andUserIdEqualTo(vo.getId());
        criteria.andCreateTimeBetween(start, end);
        List<CJourney> journeys = new ArrayList<CJourney>();
        try {
            journeys = this.getCJourneyMapper().selectByExample(search);
        } catch (Exception e) {
            logger.error("select Journey error : {}", e);
            throw new BusinessException("数据查询失败");
        }
        if (CollectionUtils.isNotEmpty(journeys) && journeys.size() > 0) {
            return "T";
        } else {
            return "F";
        }
    }

    /**
     * 构建上报日期数组
     *
     * @param journeys
     * @return
     */
    private List<String> buildDateList(List<CJourney> journeys) {
        List<String> strList = new ArrayList<String>();
        if (CollectionUtils.isNotEmpty(journeys) && journeys.size() > 0) {
            for (int i = 0; i < journeys.size(); i++) {
                SimpleDateFormat sdf = new SimpleDateFormat("MM月dd日");
                String str = sdf.format(journeys.get(i).getCreateTime());
                if (!strList.contains(str)) {
                    strList.add(str);
                }
            }
        }
        return strList;
    }

    @Override
    public LoadJourneyPageVo loadJourney() throws Exception {
        logger.info("Start to perform JourneyServiceImpl.loadJourney");
        UserVo vo = this.getUserService().getCurrentUserVo();
        logger.info("current user id : {}", vo.getId());
        SUser user = this.getUserService().getById(vo.getId());
        LoadJourneyPageVo pageVo = new LoadJourneyPageVo();
        if (StringUtils.isNotBlank(user.getPic())) {
            pageVo.setHeadUrl(QiniuUtils.generateDownloadTicket("", user.getPic(), "2", "200", "200"));
        }
        CWaybillExample example = new CWaybillExample();
        example.createCriteria().andActDriverEqualTo(vo.getId()).andIsVeneerEqualTo(false).andStatusEqualTo(WaybillStatusEnum.DONE.getValue());
        int records = 0;
        records = this.getCWaybillMapper().countByExample(example);
        pageVo.setBill(records);
        logger.info("Perform JourneyServiceImpl loadJourney end");
        return pageVo;
    }

    @Override
    public LoadJourneyPageVo loadJourneyCity() throws Exception {
        logger.info("Start to perform JourneyServiceImpl.loadJourney");
        UserVo vo = this.getUserService().getCurrentUserVo();
        logger.info("current user id : {}", vo.getId());
        SUser user = this.getUserService().getById(vo.getId());
        LoadJourneyPageVo pageVo = new LoadJourneyPageVo();
        if (null == user) {
            logger.info("current user is null");
            throw new BusinessException("当前用户不存在");
        }
        if (StringUtils.isNotBlank(user.getPic())) {
            pageVo.setHeadUrl(QiniuUtils.generateDownloadTicket("", user.getPic(), "2", "200", "200"));
        }
        CWaybillExample example = new CWaybillExample();
        example.createCriteria().andActDriverEqualTo(vo.getId()).andIsVeneerEqualTo(true).andStatusEqualTo(SServiceOrderStatusEnum.DONE.getValue());
        int records = 0;
        records = this.getCWaybillMapper().countByExample(example);
        pageVo.setBill(records);
        String realName = user.getRealName();
        if (StringUtils.isEmpty(realName)) {
            pageVo.setRealName(user.getPhone());
        } else {
            pageVo.setRealName(user.getRealName());
        }
        pageVo.setUserName(user.getName());
        logger.info("Perform JourneyServiceImpl loadJourney end");
        return pageVo;
    }

    @Override
    public LoadJourneyPageVo loadJourney(DateTime dt) throws Exception {
        logger.info("Start to perform JourneyServiceImpl.loadJourney");
        UserVo vo = this.getUserService().getCurrentUserVo();
        logger.info("current user id : {}", vo.getId());
        SUser user = this.getUserService().getById(vo.getId());
        LoadJourneyPageVo pageVo = new LoadJourneyPageVo();
        if (StringUtils.isNotBlank(user.getPic())) {
            pageVo.setHeadUrl(QiniuUtils.generateDownloadTicket("", user.getPic(), "2", "200", "200"));
        }

        DateTime startOfMonth = dt.dayOfMonth().withMinimumValue().withTimeAtStartOfDay();
        DateTime endOfMonth = dt.dayOfMonth().withMaximumValue().millisOfDay().withMaximumValue();

        CWaybillExample example = new CWaybillExample();
        //得到该司机的当月所有的已完成的运单
        example.createCriteria().andActDriverEqualTo(vo.getId()).andIsVeneerEqualTo(true).andCreateTimeBetween(startOfMonth.toDate(), endOfMonth.toDate()).andStatusEqualTo(WaybillStatusEnum.DONE.getValue());
        int records = 0;
        records = this.getCWaybillMapper().countByExample(example);
        pageVo.setBill(records);
        // 添加星级
        pageVo.setStarLevel(3);
        String mess = "您现在是三星级司机，本月已完成" + records + "单";
        pageVo.setStarMess(mess);
        pageVo.setRealName(StringUtils.isBlank(user.getRealName()) ? user.getPhone() : user.getRealName());
        pageVo.setUserName(StringUtils.isBlank(user.getName()) ? user.getPhone() : user.getName());
        // 查询当前用户在途运单
        Map<String, Object> map = this.getCWaybillVeneerService().getAlreadyGrabListByPage(new PageVo());
        if (null != map && map.size() > 0) {
            List<CWaybill> cWaybills = (List<CWaybill>) map.get("waybills");
            if (CollectionUtils.isNotEmpty(cWaybills)) {
                pageVo.setStatus("30");//执行中
                return pageVo;
            }
        }
        if (UserStatusEnum.T.getValue() == user.getUserStatus()) {// 在线
            pageVo.setStatus("40");//待接单
            return pageVo;
        } else {// 下线
            pageVo.setStatus("10");//上线接单
            return pageVo;
        }
    }

    private CJourneyMapper getCJourneyMapper() {
        return this.cJourneyMapper;
    }

    private UserService getUserService() {
        return this.userService;
    }

    private CWaybillMapper getCWaybillMapper() {
        return this.cWaybillMapper;
    }

    @Override
    public CJourney todaylastJourney() throws Exception {
        UserVo vo = this.getUserService().getCurrentUserVo();
        Date start = DateUtils.StrToDate(DateUtils.getCurrentZeroDate());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd 23:59:59");
        Date end = DateUtils.StrToDate(sdf.format(new Date()));
        CJourneyExample search = new CJourneyExample();
        search.setOrderByClause("id desc");
        CJourneyExample.Criteria criteria = search.createCriteria();
        criteria.andUserIdEqualTo(vo.getId());
        criteria.andCreateTimeBetween(start, end);
        List<CJourney> journeys = new ArrayList<CJourney>();
        try {
            journeys = this.getCJourneyMapper().selectByExample(search);
        } catch (Exception e) {
            logger.error("select Journey error : {}", e);
            throw new BusinessException("数据查询失败");
        }
        if (CollectionUtils.isNotEmpty(journeys) && journeys.size() > 0) {
            return journeys.get(0);
        }
        return null;
    }

}
